<?php

/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/6/29
 */

namespace backend\traits;

trait Singleton
{
    /**
     * @var static[] static instances in format: `[className => object]`
     */
    private static $_instances = [];

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    /**
     * Returns static class instance, which can be used to obtain meta information.
     * @param bool $refresh whether to re-create static instance even, if it is already cached.
     * @return static class instance.
     */
    public static function instance($refresh = false)
    {
        $className = get_called_class();
        if ($refresh || !isset(self::$_instances[$className])) {
            self::$_instances[$className] = \Yii::createObject($className);
        }
        return self::$_instances[$className];
    }
}